﻿using Dapper;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;

namespace DBBase
{
    public class DBConnection: IDisposable
    {
        private static string _connectionString = "";
        public static string connectionString
        {
            get
            {
                if (string.IsNullOrEmpty(_connectionString)) _connectionString = ConfigurationManager.AppSettings["MysqlDbConnectionString"];
                return _connectionString;
            }
        }
        private MySqlConnection conn;
        public DBConnection()
        {
            try
            {
                conn = new MySqlConnection(connectionString);
                conn.Open();
            }
            catch (Exception e)
            {
                Common.LogHelper.InfoError("数据库Query查询错误。" + e.Message);
                throw e;
            }
        }
        public MySqlTransaction begin()
        {
            return conn.BeginTransaction();
        }
        public List<T> QueryList<T>(string sql, object param = null)
        {
            try
            {
                return conn.Query<T>(sql, param).ToList();
            }
            catch (Exception e)
            {
                Common.LogHelper.InfoError("数据库Query查询错误。" + e.Message);
                throw e;
            }
        }
        public T QueryModel<T>(string sql, object param = null)
        {
            try
            {
                return conn.Query<T>(sql, param).SingleOrDefault();
            }
            catch (Exception e)
            {
                Common.LogHelper.InfoError("数据库Query查询错误。" + e.Message);
                throw e;
            }
        }
        public int Execute(string sql, object param = null)
        {
            try
            {
                return conn.Execute(sql, param);
            }
            catch (Exception e)
            {
                Common.LogHelper.InfoError("数据库Query查询错误。" + e.Message);
                throw e;
            }
        }
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }
        public void Dispose(bool disposing)
        {
            if (disposing)
            {
                //清理
                conn.Close();
                conn.Dispose();
            }
        }
        ~DBConnection()
        {
            this.Dispose(false);
        }
    }
}
